import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:loxen/mode/inspiration/inspiration_info_bean.dart';
import 'package:loxen/mode/study/study_info_bean.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:rxdart/rxdart.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:loxen/api/http_server/like.dart';
import 'package:loxen/mode/mine/like_list.dart';
import 'package:loxen/viewmode/mine_user_info_viewmodel.dart';
import 'package:loxen/viewmode/base_view_model.dart';

class LikeWidget extends StatelessWidget {
  const LikeWidget({Key key}) : super(key: key);

  Widget _createCountBar(double width, double height, {String iconPath, String count}) {
    return Container(
      margin: const EdgeInsets.only(right: 20.5),
      child: Row(
        children: <Widget>[
          Container(
            margin: const EdgeInsets.only(right: 3),
            child: Image.asset(
              iconPath,
              height: height,
              width: width,
              fit: BoxFit.cover,
            ),
          ),
          Text(
            count,
            style: TextStyle(
              color: Color(0xFF999999),
              fontSize: 18.sp,
              fontWeight: FontWeight.w500,
            ),
          )
        ],
      ),
    );
  }

  // 跳转到详情
  _detailRouter(BuildContext context, String id, String type) {
    switch (type) {
      case 'idea-article':
        InspirationInfo myWorks = InspirationInfo();
        myWorks.id = int.parse(id);
        Navigator.of(context).pushNamed(Routes.inspiration_detail, arguments: myWorks);
        break;
      case 'material-product':
        Navigator.of(context).pushNamed(Routes.material_detail, arguments: int.parse(id));
        break;
      case 'study-knowledge':
        StudyInfo entity = StudyInfo();
        entity.id = int.parse(id);
        int category = 0;
        Navigator.of(context).pushNamed(Routes.study_detail,
            arguments: {"detail": entity, "currentCategory": category});
        break;
      case 'study-case':
        StudyInfo entity = StudyInfo();
        entity.id = int.parse(id);
        int category = 1;
        Navigator.of(context).pushNamed(Routes.study_detail,
            arguments: {"detail": entity, "currentCategory": category});
        break;
      case 'idea-picture':
        print('跳转到灵感采集');
        break;
      default:
    }
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<_LikeViewModel>(create: (context) {
      String userId = Provider.of<MineUserInfoViewModel>(context, listen: false).user.id.toString();
      return _LikeViewModel(userId);
    }, builder: (context, _) {
      BaseState state = context.select<_LikeViewModel, BaseState>((value) => value.mState);
      List<Widget> listW = [];
      listW.add(Padding(
        padding: EdgeInsets.only(left: 36.w, top: 39.h),
        child: Text(
          '点赞',
          style: TextStyle(
            fontSize: 32.sp,
            color: Theme.of(context).textTheme.bodyText2.color,
            fontWeight: FontWeight.bold,
          ),
        ),
      ));
      if (state == BaseState.LOADING) {
        listW.add(Container(
          height: 470.h,
          child: Center(
            child: Container(
              width: 50.w,
              height: 50.w,
              child: CircularProgressIndicator(),
            ),
          ),
        ));
      }
      if (state == BaseState.EMPTY) {
        listW.add(Container(
          padding: EdgeInsets.only(top: 40.h),
          height: 470.h,
          child: Center(
            child: Column(
              children: <Widget>[
                Image.asset(
                  "images/empty.png",
                  width: 257.w,
                  height: 240.h,
                ),
                Text(
                  "还没有赞过的作品",
                  style: TextStyle(
                    fontSize: 24.sp,
                    color: Color(0X9982868E),
                  ),
                )
              ],
            ),
          ),
        ));
      }
      if (state == BaseState.FAIL) {
        listW.add(Container(
          padding: EdgeInsets.only(top: 40.h),
          height: 470.h,
          child: Center(
            child: Column(
              children: <Widget>[
                Image.asset(
                  "images/fail.png",
                  width: 257.w,
                  height: 240.h,
                ),
                Text(
                  "网络异常",
                  style: new TextStyle(
                    fontSize: 24.sp,
                    color: Color(0X9982868E),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 10.h),
                  child: SizedBox(
                    width: 260.w,
                    height: 92.h,
                    child: new OutlineButton(
                      color: Colors.white,
                      textColor: Color(0XFF0CABCB),
                      child: new Text('点我'),
                      onPressed: () {
                        context.read<_LikeViewModel>().loadData();
                      },
                      borderSide:
                          BorderSide(color: Colors.blue, width: 1.w, style: BorderStyle.solid),
                    ),
                  ),
                )
              ],
            ),
          ),
        ));
      }
      if (state == BaseState.CONTENT) {
        return Builder(builder: (context) {
          List<Widget> listW = [];
          listW.add(Padding(
            padding: EdgeInsets.only(left: 36.w, top: 39.h),
            child: Text(
              '点赞',
              style: TextStyle(
                fontSize: 32.sp,
                color: Theme.of(context).textTheme.bodyText2.color,
                fontWeight: FontWeight.bold,
              ),
            ),
          ));
          var data =
              context.select<_LikeViewModel, List<MineLike>>((value) => value.data).map((item) {
            return GestureDetector(
              onTap: () {
                _detailRouter(context, item.instance_id, item.content_type);
              },
              child: Column(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.fromLTRB(36.w, 40.h, 40.w, 40.h),
                    child: Row(
                      children: <Widget>[
                        CachedNetworkImage(
                          imageUrl: ImageUrlUtil.getClean(item.cover, w: 120),
                          height: 120.h,
                          width: 120.h,
                          fit: BoxFit.cover,
                        ),
                        Expanded(
                          child: Container(
                            height: 120.h,
                            margin: EdgeInsets.only(left: 30.w),
                            child: Column(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text.rich(
                                  TextSpan(children: <TextSpan>[
                                    TextSpan(
                                        text: '赞了 ',
                                        style: TextStyle(
                                            color: Color(0xFF999999), fontSize: 22.sp, height: 1)),
                                    TextSpan(
                                        text: item.user?.nickname ?? "",
                                        style: TextStyle(
                                            color: Color(0xFF000000), fontSize: 22.sp, height: 1)),
                                    TextSpan(
                                        text: ' 的作品',
                                        style: TextStyle(
                                            color: Color(0xFF999999), fontSize: 22.sp, height: 1)),
                                  ]),
                                  softWrap: true,
                                ),
                                Text(
                                  item.title.toString(),
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                  style: TextStyle(
                                      color: Color(0xFF000000),
                                      fontSize: 28.sp,
                                      fontWeight: FontWeight.w600,
                                      height: 1),
                                ),
                                Row(
                                  children: <Widget>[
                                    _createCountBar(25.w, 24.w,
                                        iconPath: 'images/like.png',
                                        count: item.like_num.toString()),
                                    item.content_type == 'material-product'
                                        ? SizedBox.shrink()
                                        : _createCountBar(20.w, 20.w,
                                            iconPath: 'images/comment@2x.png',
                                            count: item.comment_num.toString()),
                                  ],
                                )
                              ],
                            ),
                          ),
                        ),
                        Container(
                          width: 40.w,
                          height: 40.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage('images/like_true.png'),
                            ),
                          ),
//                          child: Image.asset('images/like_love.png',
//                              width: 20.w, height: 17.w, fit: BoxFit.cover),
                        )
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 36.w, right: 36.w),
                    color: Color(0xFFEBECF1),
                    width: double.infinity,
                    height: 0.5,
                  )
                ],
              ),
            );
          }).toList();
          listW.addAll(data);
          if (Provider.of<_LikeViewModel>(context, listen: false).isNext()) {
            listW.add(loadButton(() {
              Provider.of<_LikeViewModel>(context, listen: false).next();
            }));
          }
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: listW,
          );
        });
      }

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: listW,
      );
    });
  }

  Widget loadButton(Function() onClick) {
    ValueNotifier<bool> _click = ValueNotifier(false);
    return ValueListenableProvider.value(
        value: _click,
        child: GestureDetector(
          onTap: () {
            if (!_click.value) {
              onClick.call();
              _click.value = true;
            }
          },
          child: Container(
            width: double.infinity,
            height: 120.h,
            child: Center(
              child: Builder(
                builder: (BuildContext context) {
                  bool click = context.watch<bool>();
                  return click
                      ? Container(
                          width: 50.w,
                          height: 50.w,
                          child: CircularProgressIndicator(),
                        )
                      : Text(
                          '更多点赞',
                          style: TextStyle(
                              fontSize: 24.sp,
                              color: Color(
                                0xFF999999,
                              )),
                        );
                },
              ),
            ),
          ),
        ));
  }
}

class _LikeViewModel extends BaseViewModel with LikeMixin {
  final String userId;

  LikeList likeList;
  List<MineLike> data;
  int pageSize = 3;
  int page = 1;

  _LikeViewModel(this.userId) {
    loadData();
  }

//  void unFollowerSB(Follower follower, {Function(String error) onError}) {
//    unFollowerUser(follower.user.userId.toString()).listen((event) {
//      if (event == 200) {
//        follower.mutual_following = 0;
//        notifyListeners();
//      } else {
//        if (onError != null) onError.call("取消关注失败");
//      }
//    }, onError: (error, stack) {
//      if (onError != null) onError.call("网络异常");
//      print(error);
//      print(stack);
//    });
//  }
//
//  void followerSB(Follower follower, {Function(String error) onError}) {
//    followerUser(follower.user.userId.toString()).listen((event) {
//      if (event == 201) {
//        follower.mutual_following = 1;
//        notifyListeners();
//      } else {
//        if (onError != null) onError.call("关注失败");
//      }
//    }, onError: (error, stack) {
//      if (onError != null) onError.call("网络异常");
//      print(error);
//      print(stack);
//    });
//  }

  void next() {
    if (isNext()) {
      page += 1;
      userLikes(userId: userId, page: page.toString(), pageSize: pageSize.toString()).listen(
          (event) {
        if (event != null) {
          likeList = event;
          data = data.take(data.length).toList();
          data.addAll(event.results);
          notifyListeners();
        }
      }, onError: (error, stack) {
        print(error);
        print(stack);
      });
    }
  }

  bool isNext() {
    return likeList != null && likeList.next.trim() != '';
  }

  void loadData() {
    userLikes(userId: userId, pageSize: pageSize.toString()).doOnListen(() {
      mState = BaseState.LOADING;
      notifyListeners();
    }).listen((event) {
      if (event != null && event.results != null && event.results.length > 0) {
        likeList = event;
        data = event.results;
        mState = BaseState.CONTENT;
      } else {
        mState = BaseState.EMPTY;
      }
    }, onError: (error, stack) {
      mState = BaseState.FAIL;
      print(error);
      print(stack);
    }, onDone: () => notifyListeners());
  }
}
